package learn_security;

public class CaesarCipher {

	private static char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
//	private static char[] alphabet = "JECEHHEM".toCharArray();
	private static final int TOTAL = alphabet.length;

	public static void main(String[] args) {
//		int key = 54;
//		String msg = "summer".toUpperCase();
//
//		System.out.println("decrypt ... ");
//		String decrypted = decrypt(msg, key);
//		System.out.println(decrypted);
//
//		System.out.println("encrypt ... ");
//		System.out.println(msg + " == " + encrypt(decrypted, key));
		
		String msg = "YES";
		int key = 16;
		System.out.println(encrypt(msg, key));

	}

	private static String encrypt(String msg, int offset) {
		char[] msgArray = msg.toCharArray();
		for (int i = 0; i < msgArray.length; i++) {
			int index = getIndex(msgArray[i]);
			msgArray[i] = alphabet[(index + offset) % TOTAL];
		}
		return new String(msgArray);
	}

	private static String decrypt(String msg, int offset) {
		char[] msgArray = msg.toCharArray();
		for (int i = 0; i < msgArray.length; i++) {
			int index = getIndex(msgArray[i]);
			msgArray[i] = alphabet[(index + (TOTAL - offset % TOTAL)) % TOTAL];
		}
		return new String(msgArray);
	}

	private static int getIndex(char c) {
		for (int i = 0; i < TOTAL; i++) {
			if (c == alphabet[i]) {
				return i;
			}
		}
		throw new IllegalArgumentException(c + " not found");
	}

}
